package com.kly.msg.serviceImpl;

import com.fqgj.common.api.Response;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.kly.dto.MsgResultDto;
import com.kly.dto.SmsBackRequestDTO;
import com.kly.dto.SmsConfigRequestDTO;
import com.kly.dto.SmsRequestDTO;
import com.kly.enums.AppEnum;
import com.kly.enums.ProviderEnum;
import com.kly.msg.config.NXConfig;
import com.kly.msg.constant.ApiRedisKeys;
import com.kly.msg.db.dao.TMessageConfigBehaviorDao;
import com.kly.msg.db.entity.TMessageConfigBehaviorEntity;
import com.kly.msg.strategy.SmsStrategy;
import com.kly.msg.strategy.StrategyHelper;
import com.kly.service.PushMsgService;
import com.kly.service.SMSService;
import com.nxcloud.sdk.NxSmsClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;
import java.util.Random;

@Service("sMSService")
public class SMSServiceImpl implements SMSService {
    private static Log LOGGER = LogFactory.getLog(SMSServiceImpl.class);
    @Autowired
    NXConfig nxConfig;

    private final String SUCCESS = "0";

    @Autowired
    RedisService redisService;

    @Autowired
    StrategyHelper strategyHelper;

    @Autowired
    TMessageConfigBehaviorDao tMessageConfigBehaviorDao;

    /**
     * @param requestDTO
     */
    @Override
    public MsgResultDto sendSMS(SmsRequestDTO requestDTO) {

        Long smsProviderCode = redisService.getNumber(ApiRedisKeys.SMS_PROVIDER.getValue());
//        String smsProviderCode = "2";

        if(smsProviderCode == null|| ProviderEnum.NXY.getCode().equals(Integer.valueOf(String.valueOf(smsProviderCode)))) {
            String appKey = nxConfig.getApiKey();
            String secretKey = nxConfig.getApiSecret();

            // 这个类不是线程安全的，请每次调用，都重新初始化一个！
            NxSmsClient nxSmsClient = new NxSmsClient(appKey, secretKey);
            MsgResultDto msgResultDto = new MsgResultDto();
            msgResultDto.setPhone(requestDTO.getPhone());

            Map<String, String> result = null;
            try {
                nxSmsClient
                        .param("source_address", "meboo") // sender，发件人，请勿随意填写！
//                    .param("country_code", "91")
//                    .param("task_time", "2021-04-02 12:59:59") // 定时发送
//                    .param("sys_messageid", "") // 可以选择自己生成消息ID
//                    .param("short_link", "") // 短链
//                    .param("linkVerbose", "") // 是否追踪短链点击的手机号码（可能会降低SMS短信成功率）
//                    .param("opt_entity_id", "") //印度 dlt，91 方向实体编号
//                    .param("opt_template_id", "") //印度 dlt，91 方向模板编号
//                    .param("opt_header_id", "") //印度 dlt，91 方向发件人编号
                ;
                Random random = new Random();
                int verificationCode = 100000 + random.nextInt(900000);
                msgResultDto.setContent(String.valueOf(verificationCode));
                result = nxSmsClient.mtsend(requestDTO.getPhone(),
                        "[Meboo] Code: " + verificationCode + ", if you do not operate by yourself, ignore it.");
                LOGGER.info("sendSMSResult:{}", result);
                if (!result.get("code").equals(SUCCESS)) {
                    msgResultDto.setContent(null);
                }
            } catch (Exception e) {
                msgResultDto.setContent(null);
            }
            return msgResultDto;
        }else{
            SmsStrategy smsStrategy = strategyHelper.getStrategy(Integer.valueOf(String.valueOf(smsProviderCode)));
            SmsRequestDTO smsRequestDTO = new SmsRequestDTO();
            smsRequestDTO.setPhone(requestDTO.getPhone());
            smsRequestDTO.setAppCode(AppEnum.MECHAT.getId());

            MsgResultDto msgResultDto = smsStrategy.sendSms(smsRequestDTO);
            return  msgResultDto;
        }

    }


    @Override
    public Response<Boolean> smsCallBack(SmsBackRequestDTO smsBackRequestDTO) {
        SmsStrategy smsStrategy = strategyHelper.getStrategy(ProviderEnum.ITNIO_TECH.getCode());

        return Response.ok(smsStrategy.smsCallBack(smsBackRequestDTO));
    }

    @Transactional
    @Override
    public Boolean updateSmsConfig(SmsConfigRequestDTO requestDTO) {

        
        //修改保存redis
        redisService.setNumber(ApiRedisKeys.SMS_PROVIDER.getValue(),requestDTO.getProviderEnum().getCode());

        //修改成功保存配置修改操作记录
        TMessageConfigBehaviorEntity tMessageConfigBehaviorEntity = new TMessageConfigBehaviorEntity();
        tMessageConfigBehaviorEntity.setConfigType(requestDTO.getProviderEnum().getCode());
        tMessageConfigBehaviorDao.insert(tMessageConfigBehaviorEntity);
        return true;
    }
}
